package com.atguigu.flink.timeAndwindow;

import com.atguigu.flink.func.ClickSource;
import com.atguigu.flink.pojo.Event;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.time.Duration;

/**
 * Created by 黄凯 on 2023/6/16 0016 19:51
 *
 * @author 黄凯
 * 永远相信美好的事情总会发生.
 */
public class Flink02_FlinkEmbeddedWaterMark {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<Event> ds = env.addSource(new ClickSource());

        //有序流水位线生成
        ds.assignTimestampsAndWatermarks(

                WatermarkStrategy.<Event>forMonotonousTimestamps()
                        .withTimestampAssigner(

                                new SerializableTimestampAssigner<Event>() {


                                    @Override
                                    public long extractTimestamp(Event element, long recordTimestamp) {


                                        return element.getTs();


                                    }
                                }

                        )

        );

        //乱序流加延迟，水位线的生成
        ds.assignTimestampsAndWatermarks(

                //2秒乱序程度，或者2秒延迟
                WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                        .withTimestampAssigner(
                                (element, ts) -> element.getTs()
                        )

        );

        env.execute();

    }

}
